#include "xparameters.h"
#include <xbasic_types.h>
#include <xio.h>
#include "xtmrctr.h"

#include "lcd.h"
#include "complex.h"
#include "trig.h"
#include "spi.h"
#include "note.h"
#include "fft.h"

static float q[512];
static float w[512];

main() {		
	int m=9; //2^m=samples
	int samples=512; //any time samples is changed, n and the array size of floats must be changed
	float sample_f;
	int l;
	int ticks; //used for timer
	Xuint32 Control;
	float frequency; 
	float tot_time; //time to run program
	float clk=50000000.0; //clock speed in hz for time measurement
 
	while(1) { 
		//set up timer
		XTmrCtr timer;
		XTmrCtr_Initialize(&timer, XPAR_XPS_TIMER_0_DEVICE_ID);
		Control = XTmrCtr_GetOptions(&timer, 0) | XTC_CAPTURE_MODE_OPTION | XTC_INT_MODE_OPTION;
		XTmrCtr_SetOptions(&timer, 0, Control);
		XTmrCtr_Start(&timer, 0); 
 
		spi_read(q,samples);
		ticks=XTmrCtr_GetValue(&timer, 0); 
		
		//find sample frequency
		sample_f=ticks/clk; 
		//xil_printf("sample time: %dms\r\n",(int)(sample_f*1000));
		sample_f=samples/sample_f; 
		//xil_printf("sample frequency: %d \r\n",(int)sample_f);
		
		//zero w array
		for(l=0;l<samples;l++)
			w[l]=0; 
		
		frequency=fft(q,w,samples,m,sample_f);

		//ignore noise below set frequency
		if(frequency > 200.0) {
			DisplayClear();
 			SetCursor(1,1);
			WriteString("F:");
			WriteInt((int)(frequency+.5));
			WriteString(" Hz");

			SetCursor(2,1);
			findNote(frequency);

			//get time to run program
			ticks=XTmrCtr_GetValue(&timer, 0);
			XTmrCtr_Stop(&timer, 0);
			tot_time=ticks/clk;
			xil_printf("program time: %dms \r\n",(int)(1000*tot_time));	
		}
	}
   return 0;
}
